package com.ys.controller.api.hr;

import com.ys.config.MenuId;
import com.ys.entity.hr.ThrUserArchives;
import com.ys.entity.sys.YsCol;
import com.ys.service.hr.ThrUserArchivesRecordService;
import com.ys.service.hr.ThrUserArchivesService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 *员工档案表
 */
@Controller
@RequestMapping("/api/inter/thrUserArchives")
public class ApiInterThrUserArchivesController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterThrUserArchivesController.class);

    @Autowired
    private CommonApiService<ThrUserArchives> commonApiService;
    @Autowired
    private ThrUserArchivesService thrUserArchivesService;
    @Autowired
    private ThrUserArchivesRecordService thrUserArchivesRecordService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public ThrUserArchives setSeachSql(ThrUserArchives cond){

        //cond.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS auditingTime");
        cond.addField("A.HeadUserId + '/' + U.UserName AS headUserName");
        cond.addField("O.DeptName AS deptName");
        cond.addField("R.Name AS roleName");
        cond.addField("BA1.HigherLevelPath + ',' + BA1.Name AS nativePlaceName");
        cond.addField("BA2.HigherLevelPath + ',' + BA2.Name AS workCityName");
        cond.addField("B.VReMark AS officeName");
        //cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ");
        cond.addLeftJoin("TS_OrganizationInfo O ON O.Orgid = A.DeptId AND 1=1");
        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.HeadUserId AND 1=1");
        cond.addLeftJoin("YS_Role R ON R.Id = A.RoleId AND 1=1");
        cond.addLeftJoin("TB_BaseInfoArea BA1 ON BA1.Code = A.NativePlace AND 1=1");
        cond.addLeftJoin("TB_BaseInfoArea BA2 ON BA2.Code = A.WorkCity AND 1=1");
        cond.addLeftJoin("TB_BaseInfo B ON B.Id = A.OfficeId AND 1=1");

        //排序
        cond.setOrderby("A.ArchivesBid DESC");
        cond = commonApiService.dataAuth(MenuId.THR_UserArchives, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("thrUserArchives:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute ThrUserArchives cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute ThrUserArchives cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.THR_UserArchives)
                    .where("A.Code != 'ope'")
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<ThrUserArchives> util = new ExportExcelUtils<>(new ThrUserArchives());
            String toFilePath = util.exportExcel(listData, listField, "员工档案");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 编辑
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return thrUserArchivesService.update(params,MenuId.THR_UserArchives);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 删除员工档案过错与奖励记录表
     */
    @RequestMapping("/toDelRecord")
    @ResponseBody
    public R toDelRecord(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            for(int i=0;i<idList.size();i++) {
                //删除
                thrUserArchivesRecordService.del(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        }catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }

    }





}